package com.qf.servlet;

import com.qf.constant.MyConstant;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImp;
import com.qf.utils.MD5Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet( "/userLoginServlet")
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding ( "utf-8" );
        response.setContentType ( "text/html;charest=utf-8" );

        //校验验证码

        //获取前台验证码
        String userCode = request.getParameter ( "userCode" );

        //获取服务端验证码
        HttpSession session = request.getSession ( );

        String checkcode_server = (String) session.getAttribute ( "CHECKCODE_SERVER" );

        session.getAttribute ( "CHECKCODE_SERVER" );
        session.removeAttribute ( "CHECKCODE_SERVER" );

        if (userCode==null || !userCode.equals ( checkcode_server )){
            request.setAttribute ( "msg","验证码输入错误请重新输入" );
            request.getRequestDispatcher ( "/jsp/login.jsp" ).forward ( request,response );
        }
        //如果验证码一致

        String username = request.getParameter ( "username" );
        String password = request.getParameter ( "password" );

        //密码加密
        password=MD5Utils.md5 ( password );

        //调用业务层接口

        UserService userService = new UserServiceImp ();

        User user =userService.findUserByNameAndPassword(username,password);


        if (user==null){

            request.setAttribute ( "msg","用户名或密码输入错误" );

            request.getRequestDispatcher ( "/jsp/login.jsp" ).forward ( request,response );
        }

        if (user.getState ()==0){
            request.setAttribute("msg","用户未激活,<a href='/aaa_war/userActive?code="+user.getCode()+"'>请激活</a>");
            request.getRequestDispatcher ( "/jsp/login.jsp" ).forward ( request,response );
            System.out.println (user.getState () );
        }
        //如果对象已激活
        //重定向到首页
        session.setAttribute ( "user",user );

        response.sendRedirect (request.getContextPath ()+"/" );






    }

    protected void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        doPost ( request,response );
    }
}
